package pers.llc.css.condition;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;


/**
 * @author fancy
 * @time 2018-09-30
 */
public class BoundedBuffer {

    final Lock lock = new ReentrantLock();
    final Condition notFull = lock.newCondition();
    final Condition notEmpty = lock.newCondition();

    final Object[] items = new Object[3];
    private int puts, takes, count;

    public void put(Object x) throws InterruptedException {
        lock.lock();
        try {
            //说明队列已满，需要等待（测试条件谓词）
            while (count == items.length) {
                notFull.await();
            }
            if (++puts == items.length) {
                puts = 0;
            }
            ++count;
            notEmpty.signal();
            System.out.println("put:" + x);
        } finally {
            lock.unlock();
        }
    }

    public Object take(Object x) throws InterruptedException {
        lock.lock();
        try {
            //说明队列元素为空，没有值可等待值的插入（测试条件谓词）
            while (count == 0) {
                notEmpty.await();
            }
            if (++takes == items.length) {
                takes = 0;
            }
            --count;
            notFull.signal();
            System.out.println("take:" + x);
            return x;
        } finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        BoundedBuffer buffer = new BoundedBuffer();
        new Thread(()->{
            try {
                buffer.put("1");
                buffer.put("2");
                buffer.put("3");
                buffer.put("4");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }).start();

        new Thread(()->{
            try {
                buffer.take("3");
                buffer.take("2");
                buffer.take("4");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }).start();

        System.out.println("ok");
    }
}
